package com.example.bootdemo.factory;

import org.springframework.data.jpa.domain.Specification;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;

public final class SpecificationFactory {

    /**
     * 模糊查询，匹配对应字段
     * @param attribute
     * @param value
     * @return
     */
    public static Specification containsLike(String attribute,String value){

        return (root, query, cb) -> cb.like(root.get(attribute),"%"+value+"%");

    }

    /**
     * 获取某字段等于value的查询条件
     * @param attribute
     * @param value
     * @return
     */
    public static Specification equal(String attribute,Object value){

        return (root,query,cb)->cb.equal(root.get(attribute),value);
    }

    /**
     * 插叙某字段在一个区间的范围
     * @param attribute
     * @param min
     * @param max
     * @return
     */
    public static Specification isBetween(String attribute,int min,int max){

        return (root,query,cb)->cb.between(root.get(attribute),min,max);
    }

    public static Specification isBetween(String attribute,double min,double max){

        return (root,query,cb)->cb.between(root.get(attribute),min,max);
    }

    public static Specification isBetween(String attribute, Date min, Date max){

        return (root,query,cb)->cb.between(root.get(attribute),min,max);
    }

    /**
     * 通过属性名和集合实现In查询
     * @param attribute
     * @param c
     * @return
     */
    public static Specification in(String attribute, Collection c){

        return (root,query,cb)->root.get(attribute).in(c);
    }


    public static Specification greaterThan(String attribute, BigDecimal value){

        return (root,query,cb)->cb.greaterThan(root.get(attribute),value);
    }

    public static Specification greaterThan(String attribute, Long value){

        return (root,query,cb)->cb.greaterThan(root.get(attribute),value);
    }

}
